package br.com.mural.android;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import br.com.mural.android.entidades.Usuario;
import br.com.mural.android.util.AlertDialogManager;
import br.com.mural.android.util.GerenteSessao;
import br.com.mural.android.webservice.UsuarioRest;

public class LoginActivity extends Activity {
	EditText editLogin, editSenha;
	Button btnEntrar;
	
	GerenteSessao session;
	AlertDialogManager alert = new AlertDialogManager();
	Usuario usuario;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		
		session = new GerenteSessao(getApplicationContext());
		
		session = new GerenteSessao(getApplicationContext());
		
		editLogin = (EditText) findViewById(R.id.editLogin);
		editSenha = (EditText) findViewById(R.id.editSenha);
		
		btnEntrar = (Button) findViewById(R.id.btnEntrar);
		
		btnEntrar.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String login = editLogin.getText().toString();
				String senha = editSenha.getText().toString();
				if (login.trim().length() > 0 && senha.trim().length() > 0) {
					usuario = autentica(login, senha);
					if (usuario != null) {
						
						session.createLoginSession(usuario.getId(), usuario.getNome(), usuario.getMatricula(), usuario.getSenha());
						
						Intent i = new Intent(getApplicationContext(),MainAdminActivity.class);
						startActivity(i);
					} else {
						alert.showAlertDialog(LoginActivity.this, "Login failed..", "Login/Senha is incorrect ",
								false);
					}	
				} else {
					alert.showAlertDialog(LoginActivity.this, "Login failed..", "Please enter login and senha", false);
				}
			}
			
			private Usuario autentica(String login, String senha) {
				UsuarioRest usuarioRest = new UsuarioRest();
				try {
					usuario = usuarioRest.login(login, senha);
				} catch (Exception e) {
					e.printStackTrace();
				}
				return usuario;
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.login, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}
